package com.framework.core.mybatis.config;

import com.framework.core.mybatis.ddl.IMybatisDdlFactory;
import com.framework.core.mybatis.ddl.mysql.MysqlDdlFactory;
import com.framework.core.mybatis.ddl.pg.PostgresqlDdlFactory;
import com.framework.core.mybatis.em.DbType;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.mapping.VendorDatabaseIdProvider;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.util.ObjectUtils;

import java.util.Locale;
import java.util.Properties;

import static com.framework.core.mybatis.em.DbType.MYSQL;
import static com.framework.core.mybatis.em.DbType.POSTGRESQL;

/**
 *  配置文件读取
 *  created by zzg
 *  2024-12-06
 */
@Configuration
public class DbConfig {
    @Autowired
    private Environment env;

    @Bean
    public MybatisDdlProperties mybatisDdlProperties() {
        String database = env.getProperty("spring.datasource.driverClassName");
        String generateDdl = env.getProperty("mybatis-plus.generate-ddl");
        String typeAliasesPackage = env.getProperty("mybatis-plus.type-aliases-package");
        MybatisDdlProperties properties = new MybatisDdlProperties();
        if (ObjectUtils.isEmpty(generateDdl)) {
            properties.setGenerateDdl(false);
        } else {
            properties.setGenerateDdl(Boolean.valueOf(generateDdl));
        }

        database = database.toLowerCase(Locale.ROOT);
        if (database.contains(MYSQL.getValue())) {
            properties.setDbType(DbType.MYSQL);
        } else if (database.contains(POSTGRESQL.getValue())) {
            properties.setDbType(POSTGRESQL);
        }

        properties.setTypeAliasesPackage(typeAliasesPackage);
        return properties;
    }

    @Bean
    public IMybatisDdlFactory ddlFactory(@Autowired MybatisDdlProperties properties) {
        switch (properties.getDbType()) {
            case MYSQL:
                return new MysqlDdlFactory();
            case POSTGRESQL:
                return new PostgresqlDdlFactory();
        }

        return new MysqlDdlFactory();
    }

    /**
     * 多数据库适配
     */
    @Bean
    public DatabaseIdProvider databaseIdProvider() {
        DatabaseIdProvider databaseIdProvider = new VendorDatabaseIdProvider();
        Properties properties = new Properties();
        properties.setProperty("MySQL", "mysql");
        properties.setProperty("PostgresqL", "postgresql");
        databaseIdProvider.setProperties(properties);
        return databaseIdProvider;
    }
}
